local gamelib = require "club.threecard.gamelib"
local GameObjectExtension = CS.Blaze.GameObjectExtension
local GridLayoutGroup = typeof(CS.UnityEngine.UI.GridLayoutGroup)
local TextMeshProUGUI = typeof(CS.TMPro.TextMeshProUGUI)
local Constraint = CS.UnityEngine.UI.GridLayoutGroup.Constraint

local M = gamelib.ui.element()

local function create_symbol(self)
    local obj = GameObjectExtension.GetFromPool(self.symbol_node)
    local t = {}
    t.gameObject = obj
    t.transform = obj.transform
    t.selectd_obj = t.transform:Find("selected").gameObject
    t.unselectd_obj = t.transform:Find("unselected").gameObject

    t.active = function(t, b)
        t.selectd_obj:SetActive(b)
        t.unselectd_obj:SetActive(not b)
    end,

    table.insert(self.objs, obj)
    return t
end

local function create_group(self)
    local obj = GameObjectExtension.GetFromPool(self.group_node)
    local t = {}
    t.gameObject = obj
    t.transform = obj.transform
    t.index_txt = t.transform:Find("index_txt").gameObject:GetComponent(TextMeshProUGUI)
    t.grid = t.transform:Find("bg/root").gameObject:GetComponent(GridLayoutGroup)

    t.init = function(t, row, column, index, payline)
        t.grid.constraint = Constraint.FixedColumnCount
        t.grid.constraintCount = column

        local payline_temp = {}
        for i = 1, #payline do
            table.insert(payline_temp, tonumber(payline[i]))
        end
        payline = payline_temp

        for i = 1, row*column do
            local sym_node = create_symbol(self)
            sym_node.transform:SetParent(t.grid.transform, false)
            t.index_txt.text = index

            local current_column = ((i-1)%column+1)
            local current_row = math.floor((i-1)/column)
            sym_node:active(payline[current_column] == current_row)
        end
    end

    table.insert(self.objs, obj)
    return t
end

function M:ctor(row, column, paylines)
    self.row = row
    self.column = column
    self.paylines = paylines
    self.res = "club.threecard.slotlib/ui/common.b:rule_payline"
    self.objs = {}
    self.title = "赔付线"
end

function M:on_injected()
    for i, payline in ipairs(self.paylines) do
        local group = create_group(self)
        group.transform:SetParent(self.content, false)
        group:init(self.row, self.column, i, payline)
    end
end

function M:on_release()
    self:super("on_release")
    for _, obj in pairs(self.objs) do
        GameObjectExtension.ReturnToPool(obj)
    end
    self.objs = nil
end

return M